package com.gzhu.knowledgeAdmin.common.aspect;


import com.gzhu.knowledgeAdmin.common.annotation.MyLog;
import com.gzhu.knowledgeAdmin.common.utils.UserInfoUtils;
import com.gzhu.knowledgeAdmin.repository.UserLogRepository;
import com.gzhu.knowledgeAdmin.entity.UserLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class LogAspect {
    /**
     * 该Service及其实现类相关代码请自行实现，只是一个简单的插入数据库操作
     */
    @Autowired
    private UserLogRepository userLogRepository;

	/**
     * @annotation(MyLog类的路径) 在idea中，右键自定义的MyLog类-> 点击Copy Reference
     */
    @Pointcut("@annotation(com.gzhu.knowledgeAdmin.common.annotation.MyLog)")
    public void logPointCut() {
        log.info("------>配置织入点");
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e) {

        // 获得MyLog注解
        MyLog controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }

        UserLog userLog = new UserLog();
        // 整合-获取公司id
        String gsid = UserInfoUtils.getCurrentUser().getGsid();
        userLog.setF_GH(gsid);
//        userLog.setF_GH(UserInfoUtil.getCurrentUser().getUser().getF_ID().toString());
        userLog.setF_CZSJ(new Date());
        userLog.setF_CZMK(controllerLog.title());
        String optParam = controllerLog.optParam();
        if (e != null) {
            optParam += "(操作失败:" + e.getMessage() + ")";
        } else {
            optParam += "(操作成功)";
        }
        userLog.setF_CZNR(optParam);

        // 保存数据库
        userLogRepository.save(userLog);
    }

    /**
     * 是否存在注解，如果存在就获取，不存在则返回null
     * @param joinPoint
     * @return
     */
    private MyLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(MyLog.class);
        }
        return null;
    }

}
